package utils

import (
	"context"
	"github.com/jackc/pgx/v5/pgxpool"
	"log/slog"
	"os"
)

var (
	DB *pgxpool.Pool
)

func InitDB() {
	var err error
	ctx := context.Background()
	poolConfig, err := pgxpool.ParseConfig(os.Getenv("DATABASE_URL"))
	if err != nil {
		slog.Error("parse database config failed", "err", err)
		os.Exit(1)
	}
	DB, err = pgxpool.NewWithConfig(ctx, poolConfig)
	if err != nil {
		slog.Error("数据库连接失败,", "err", err)
		os.Exit(1)
	}
	if err = DB.Ping(ctx); err != nil {
		slog.Error("数据库异常,", "err", err)
		os.Exit(1)
	} else {
		slog.Info("connect to database success.")
	}
}
